package com.xbts.common.utils.aspose;

import com.aspose.slides.License;
import com.aspose.slides.Presentation;
import com.aspose.slides.SaveFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
 * SlidesFileConvert
 *
 * @author swx
 * @version v1.0
 * @date 2022/10/27 9:02
 */
@Component
public class SlidesFileConvert implements IFileConvert {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    private boolean getLicense() {
        boolean result = false;
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        try (InputStream is = loader.getResourceAsStream("license.xml")) {
            License license = new License();
            license.setLicense(is);
            result = true;
        } catch (Exception e) {
            log.error("获取license失败", e);
        }
        return result;
    }

    @Override
    public InputStream fileToPdf(InputStream inputStream) {
        if (!getLicense()) {
            return null;
        }
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            Presentation pres = new Presentation(inputStream);
            pres.save(byteArrayOutputStream, SaveFormat.Pdf);
            return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        } catch (Exception e) {
           log.error("ppt转pdf失败", e);
        }
        return null;
    }

    @Override
    public void afterPropertiesSet() {
        FileConvertConstant.PPT_TO_PDF.forEach(ppt -> AsposeSingleton.instance().put(ppt, this));
    }

}
